﻿/***********************************************************************
 * <copyright file="FrmXtraBaseVoucherDetail.cs" company="BUCA JSC">
 * -->    Copyright (C) statement. All right reserved
 * </copyright>
 * 
 * Created:   LinhMC
 * Email:    linhmc@buca.vn
 * Website:
 * Create Date: Thursday, February 13, 2014
 * Usage: 
 * 
 * RevisionHistory: 
 * Date         Author               Description 
 * 
 * ************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using WindowsForms.AOnline.Presenter.Dictionary.AutoNumber;
using WindowsForms.AOnline.Session;
using WindowsForms.AOnline.View.Dictionary;
using WindowsForms.AOnline.WindowsForm.CommonClass;
using WindowsForms.AOnline.WindowsForm.FormBase.PropertyGrid;
using WindowsForms.AOnline.WindowsForm.Resources;
using DevExpress.Data;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Mask;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;


namespace WindowsForms.AOnline.WindowsForm.FormBase
{
    public partial class FrmXtraBaseVoucherDetail : XtraForm,IAutoNumberView
    {
        #region AutoNumber properties

        /// <summary>
        /// Gets or sets the prefix.
        /// </summary>
        /// <value>
        /// The prefix.
        /// </value>
        public string Prefix { private get; set; }

        /// <summary>
        /// Gets or sets the suffix.
        /// </summary>
        /// <value>
        /// The suffix.
        /// </value>
        public string Suffix { private get; set; }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>
        /// The value.
        /// </value>
        public int Value { private get; set; }

        /// <summary>
        /// Gets or sets the leng of value.
        /// </summary>
        /// <value>
        /// The leng of value.
        /// </value>
        public int LengthOfValue { private get; set; }

        #endregion

        #region Variables
         /// <summary>
        /// The _auto number presenter
        /// </summary>
        private readonly AutoNumberPresenter _autoNumberPresenter;
        private DBOptionHelper _dbOptionHelper;
        private EnumNavigationStatus _navigationState;
        public BindingSource MasterBindingSource;
        public enum ActionModeEnum
        {
            AddNew = 0,
            Edit = 1,
            Delete = 2,
            None = 3
        }
        public enum RefType
        {
            ReceiptEstimate = 110,
            PaymentEstimate = 120,
            ReceiptCash = 200,
            PaymentCash = 201,
            ReceiptDeposite = 300,
            PaymentDeposite = 301,
            InwardStock = 400,
            OutwardStock = 401,
            Salary=168
        }
        private ActionModeEnum _actionMode;
        protected string CurrencyAccounting;
        protected string CurrencyAccountingUSD = "USD";
        protected DateTime SystemDate;

        /// <summary>
        /// Gets or sets the action mode.
        /// </summary>
        /// <value>
        /// The action mode.
        /// </value>
        public ActionModeEnum ActionMode
        {
            get { return _actionMode; }
            set
            {
                _actionMode = value;

                switch (_actionMode)
                {
                    case ActionModeEnum.None:
                        Text = FormCaption;
                        SetEnableToolbarControl(false);
                        break;
                    case ActionModeEnum.Edit:
                        Text = string.Format(ResourceHelper.GetResourceValueByName("ResEditText"), FormCaption);
                        SetEnableToolbarControl(true);
                        break;
                    case ActionModeEnum.AddNew:
                        Text = string.Format(ResourceHelper.GetResourceValueByName("ResAddNewText"), FormCaption);
                        SetEnableToolbarControl(true);
                        break;
                }
            }
        }

        /// <summary>
        /// The key for send
        /// </summary>
        private string _keyForSend;

        ///// <summary>
        ///// The _auto number presenter
        ///// </summary>
        //private readonly AutoNumberPresenter _autoNumberPresenter;

        /// <summary>
        /// The columns collection
        /// </summary>
        public List<XtraColumn> ColumnsCollection = new List<XtraColumn>();

        /// <summary>
        /// Gets or sets the key value.
        /// </summary>
        /// <value>
        /// The key value.
        /// </value>
        public string KeyValue { get; set; }

        /// <summary>
        /// Gets the reference no.
        /// </summary>
        /// <value>
        /// The reference no.
        /// </value>
        private string BaseRefNo { get; set; }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the reference type identifier.
        /// </summary>
        /// <value>
        /// The reference type identifier.
        /// </value>
        [Category("BaseProperty")]
        public RefType BaseRefTypeId { get; set; }

        /// <summary>
        /// Gets or sets the form caption.
        /// </summary>
        /// <value>
        /// The form caption.
        /// </value>
        [Category("BaseProperty")]
        public string FormCaption { get; set; }

        /// <summary>
        /// Gets or sets the summary in column.
        /// </summary>
        /// <value>
        /// The summary in column.
        /// </value>
        [Category("BaseProperty")]
        public string SummaryInColumn { get; set; }

        #endregion

        #region Functions

        /// <summary>
        /// Initializes the layout.
        /// </summary>
        private void InitializeLayout()
        {
            if (!DesignMode)
            {
                _dbOptionHelper = new DBOptionHelper();
              //  CurrencyAccounting = _dbOptionHelper.CurrencyAccounting;
                SystemDate = DateTime.Parse(_dbOptionHelper.SystemDate);
                if (bindingSourceDetail != null && bindingSourceDetail.DataSource != null)
                    bindingSourceDetail.DataSource = null;
                gridViewDetail.OptionsView.ShowFooter = true;
                InitControls();
            }
        }

        /// <summary>
        /// Closes the form.
        /// </summary>
        private void CloseForm()
        {
            if (PostKeyValue != null) PostKeyValue(this, _keyForSend);
            Close();
        }

        /// <summary>
        /// Generateds the reference no.
        /// </summary>
        private void GeneratedBaseRefNo()
        {
            //lay ra ma so voucher theo reftype
            BaseRefNo = "";
            if (!DesignMode)
            {
                if (ActionMode == ActionModeEnum.AddNew)
                {
                    _autoNumberPresenter.DisplayByRefType((int)BaseRefTypeId);

                    if (!String.IsNullOrEmpty(Prefix))
                    {
                        BaseRefNo += Prefix;
                    }
                    if (Value >= 0)
                    {
                        for (int i = 0; i < (LengthOfValue - Value.ToString(CultureInfo.InvariantCulture).Length); i++)
                            BaseRefNo += "0";
                        BaseRefNo += (Value + 1);
                    }
                    if (!String.IsNullOrEmpty(Suffix)) BaseRefNo += Suffix;
                    if (!String.IsNullOrEmpty(BaseRefNo)) txtRefNo.Text = BaseRefNo;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="keyValue">The key value.</param>
        public delegate void EventPostKeyHandler(object sender, string keyValue);

        /// <summary>
        /// The key value
        /// </summary>
        public event EventPostKeyHandler PostKeyValue;

        /// <summary>
        /// Loads the grid detail layout.
        /// </summary>
        protected void LoadGridDetailLayout()
        {
            if (ColumnsCollection == null) return;
            foreach (var column in ColumnsCollection)
            {
                if (column.ColumnVisible)
                {
                    gridViewDetail.Columns[column.ColumnName].Caption = column.ColumnCaption;
                    gridViewDetail.Columns[column.ColumnName].VisibleIndex = column.ColumnPosition;
                    gridViewDetail.Columns[column.ColumnName].Width = column.ColumnWith;
                    gridViewDetail.Columns[column.ColumnName].UnboundType = column.ColumnType; //dung de dinh dang so theo kieu du lieu
                }
                else
                    gridViewDetail.Columns[column.ColumnName].Visible = false;
            }
        }

        /// <summary>
        /// Sets the enable toolbar control.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        protected void SetEnableToolbarControl(bool isEnable)
        {
            barButtonAddNewItem.Enabled = !isEnable;
            barButtonDeleteItem.Enabled = !isEnable;
            barButtonEditItem.Enabled = !isEnable;
            barButtonFirstItem.Enabled = !isEnable;
            barButtonPreviousItem.Enabled = !isEnable;
            barButtonNextItem.Enabled = !isEnable;
            barButtonLastItem.Enabled = !isEnable;
            barButtonPrintItem.Enabled = !isEnable;
            barButtonRefeshItem.Enabled = !isEnable;
            barButtonCancelItem.Enabled = isEnable;
            barButtonSaveItem.Enabled = isEnable;
            barButtonAddNewRowItem.Enabled = isEnable;
            barButtonDeleteRowItem.Enabled = isEnable;

            //edit by thangnd; 20/03/2014
            EnableControlsInGroup(groupObject, isEnable);
            EnableControlsInGroup(groupVoucher, isEnable);

            SetEnableGroupBox(isEnable); // su dung cho cac form thua ke

            gridViewDetail.OptionsBehavior.Editable = isEnable;
            gridViewDetail.OptionsBehavior.ReadOnly = !isEnable;
            gridViewDetail.FocusRectStyle = DrawFocusRectStyle.None;
            gridViewDetail.OptionsSelection.EnableAppearanceFocusedCell = isEnable;
            gridViewDetail.OptionsView.NewItemRowPosition = !isEnable ? NewItemRowPosition.None : NewItemRowPosition.Bottom;
            gridViewMaster.OptionsBehavior.Editable = isEnable;
            gridViewMaster.OptionsBehavior.ReadOnly = !isEnable;
        }

        /// <summary>
        /// Refreshes the toolbar.
        /// </summary>
        protected virtual void RefreshToolbar()
        {
            switch (ActionMode)
            {
                case ActionModeEnum.None:
                    SetEnableToolbarControl(false);
                    break;
                case ActionModeEnum.Edit:
                case ActionModeEnum.AddNew:
                    SetEnableToolbarControl(true);
                    break;
            }
        }

        /// <summary>
        /// Refreshes the navigation button.
        /// </summary>
        protected virtual void RefreshNavigationButton()
        {
            switch (_navigationState)
            {
                case EnumNavigationStatus.FirstPosition:
                    barButtonFirstItem.Enabled = false;
                    barButtonPreviousItem.Enabled = false;
                    barButtonNextItem.Enabled = true;
                    barButtonLastItem.Enabled = true;
                    break;
                case EnumNavigationStatus.LastPosition:
                    barButtonFirstItem.Enabled = true;
                    barButtonPreviousItem.Enabled = true;
                    barButtonNextItem.Enabled = false;
                    barButtonLastItem.Enabled = false;
                    break;
                case EnumNavigationStatus.InsidePosition:
                    barButtonFirstItem.Enabled = true;
                    barButtonPreviousItem.Enabled = true;
                    barButtonNextItem.Enabled = true;
                    barButtonLastItem.Enabled = true;
                    break;
                case EnumNavigationStatus.EmptyPostion:
                case EnumNavigationStatus.OnlyOneRow:
                    barButtonFirstItem.Enabled = false;
                    barButtonPreviousItem.Enabled = false;
                    barButtonNextItem.Enabled = false;
                    barButtonLastItem.Enabled = false;
                    break;
            }
        }

        /// <summary>
        /// Gets or sets the state of the navigation.
        /// </summary>
        /// <value>
        /// The state of the navigation.
        /// </value>
        private EnumNavigationStatus NavigationState
        {
            get
            {
                var rowCount = BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count;
                switch (rowCount)
                {
                    case 0:
                        _navigationState = EnumNavigationStatus.EmptyPostion;
                        break;
                    case 1:
                        _navigationState = EnumNavigationStatus.OnlyOneRow;
                        break;
                    default:
                        var iCurrentPosition = BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position;
                        if (iCurrentPosition == 0)
                        {
                            _navigationState = EnumNavigationStatus.FirstPosition;
                        }
                        else if (iCurrentPosition == rowCount - 1)
                        {
                            _navigationState = EnumNavigationStatus.LastPosition;
                        }
                        else
                            _navigationState = EnumNavigationStatus.InsidePosition;
                        break;
                }

                return _navigationState;
            }
            set
            {
                _navigationState = value;
            }
        }

        /// <summary>
        /// Gets or sets the current position.
        /// </summary>
        /// <value>
        /// The current position.
        /// </value>
        public int CurrentPosition
        {
            get
            {
                if (DesignMode) return 0;
                return BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position;
            }
            set
            {
                if (DesignMode) return;
                if (ActionMode == ActionModeEnum.AddNew || ActionMode == ActionModeEnum.Edit) return;
                BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position = value;
                switch (BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count)
                {
                    case 0:
                        NavigationState = EnumNavigationStatus.EmptyPostion;
                        break;
                    case 1:
                        NavigationState = EnumNavigationStatus.OnlyOneRow;
                        break;
                    default:
                        if (value == 0)
                        {
                            NavigationState = EnumNavigationStatus.FirstPosition;
                            break;
                        }
                        if (value == BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count - 1)
                        {
                            NavigationState = EnumNavigationStatus.LastPosition;
                            break;
                        }
                        NavigationState = EnumNavigationStatus.InsidePosition;
                        break;
                }
                RefreshNavigationButton();
            }
        }

        /// <summary>
        /// Moves the first voucher.
        /// </summary>
        protected void MoveFirstVoucher()
        {
            try
            {
                if (BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count > 0)
                {
                    BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position = 0;
                    MasterBindingSource.Position =
                        BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position;
                    NavigationState = CurrentPosition <= 0
                                          ? EnumNavigationStatus.FirstPosition
                                          : EnumNavigationStatus.InsidePosition;
                    RefreshNavigationButton();
                    ShowData();
                }
                else
                {
                    NavigationState = EnumNavigationStatus.EmptyPostion;
                    RefreshToolbar();
                    RefreshNavigationButton();
                    ShowData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Moves the previous voucher.
        /// </summary>
        protected void MovePreviousVoucher()
        {
            try
            {
                if (BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count > 0)
                {
                    BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position -= 1;
                    MasterBindingSource.Position =
                        BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position;
                    NavigationState = CurrentPosition <= 0
                                          ? EnumNavigationStatus.FirstPosition
                                          : EnumNavigationStatus.InsidePosition;
                    RefreshNavigationButton();
                    ShowData();
                }
                else
                {
                    NavigationState = EnumNavigationStatus.EmptyPostion;
                    RefreshToolbar();
                    RefreshNavigationButton();
                    ShowData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Moves the next voucher.
        /// </summary>
        protected void MoveNextVoucher()
        {
            try
            {
                if (BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count > 0)
                {
                    BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position += 1;
                    MasterBindingSource.Position =
                        BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position;
                    NavigationState = CurrentPosition >=
                                      BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count - 1
                                          ? EnumNavigationStatus.LastPosition
                                          : EnumNavigationStatus.InsidePosition;
                    RefreshNavigationButton();
                    ShowData();
                }
                else
                {
                    NavigationState = EnumNavigationStatus.EmptyPostion;
                    RefreshToolbar();
                    RefreshNavigationButton();
                    ShowData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Moves the last voucher.
        /// </summary>
        protected void MoveLastVoucher()
        {
            try
            {
                var iRowCount = BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Count;
                if (iRowCount > 0)
                {
                    BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position = iRowCount - 1;
                    MasterBindingSource.Position =
                        BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position;
                    NavigationState = EnumNavigationStatus.LastPosition;
                    RefreshNavigationButton();
                    ShowData();
                }
                else
                {
                    NavigationState = EnumNavigationStatus.EmptyPostion;
                    RefreshToolbar();
                    RefreshNavigationButton();
                    ShowData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Sets the numeric format control.
        /// </summary>
        /// <param name="gridView">The grid view.</param>
        /// <param name="isSummary">if set to <c>true</c> [is summary].</param>
        protected virtual void SetNumericFormatControl(GridView gridView, bool isSummary)
        {
            //Get format data from db to format grid control
            if (!DesignMode)
            {
                var repositoryCurrencyCalcEdit = new RepositoryItemCalcEdit();
                var repositoryNumberCalcEdit = new RepositoryItemCalcEdit();
                foreach (GridColumn oCol in gridView.Columns)
                {
                    if (!oCol.Visible) continue;
                    if (oCol.Name == "colTaxRate") 
                    {
                        continue;
                    }
                    switch (oCol.UnboundType )
                    {
                        case UnboundColumnType.Decimal:
                            repositoryCurrencyCalcEdit.Mask.MaskType = MaskType.Numeric;
                            repositoryCurrencyCalcEdit.Mask.EditMask = @"c" + _dbOptionHelper.CurrencyDecimalDigits;
                            repositoryCurrencyCalcEdit.Mask.Culture = Thread.CurrentThread.CurrentCulture;
                            repositoryCurrencyCalcEdit.Mask.UseMaskAsDisplayFormat = true;
                            oCol.ColumnEdit = repositoryCurrencyCalcEdit;
                            if (isSummary)
                            {
                                oCol.SummaryItem.SummaryType = SummaryItemType.Sum;
                                oCol.SummaryItem.DisplayFormat = GlobalVariable.CurrencyDisplayString;
                                oCol.SummaryItem.Format = Thread.CurrentThread.CurrentCulture;
                            }
                            break;

                        case UnboundColumnType.Integer:
                            repositoryNumberCalcEdit.Mask.MaskType = MaskType.Numeric;
                            repositoryNumberCalcEdit.Mask.EditMask = @"n0";
                            repositoryNumberCalcEdit.Mask.UseMaskAsDisplayFormat = true;
                            repositoryNumberCalcEdit.Mask.Culture = Thread.CurrentThread.CurrentCulture;
                            oCol.ColumnEdit = repositoryNumberCalcEdit;
                            oCol.SummaryItem.DisplayFormat = GlobalVariable.NumericDisplayString;
                            oCol.SummaryItem.Format = Thread.CurrentThread.CurrentCulture;
                            break;
                   
                        case UnboundColumnType.DateTime:
                            oCol.DisplayFormat.FormatString =
                                Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;
                            oCol.DisplayFormat.Format = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// Enables the controls in group.
        /// </summary>
        /// <param name="groupControl">The group control.</param>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        protected void EnableControlsInGroup(GroupControl groupControl, bool isEnable)
        {
            foreach (var control in groupControl.Controls)
            {
                if (control.GetType() == typeof(TextEdit))
                {
                    ((TextEdit)control).Properties.ReadOnly = !isEnable;
                    ((TextEdit)control).Properties.AppearanceReadOnly.BackColor = Color.GhostWhite;
                }
                if (control.GetType() == typeof(DateEdit))
                {
                    ((DateEdit) control).Properties.Mask.Culture = Thread.CurrentThread.CurrentCulture;
                    ((DateEdit)control).Properties.Mask.UseMaskAsDisplayFormat = true;
                    ((DateEdit)control).Properties.ReadOnly = !isEnable;
                    ((DateEdit)control).Properties.AppearanceReadOnly.BackColor = Color.GhostWhite;
                    ((DateEdit)control).Properties.ShowDropDown = (!isEnable) ? ShowDropDown.Never : ShowDropDown.SingleClick;
                }
                if (control.GetType() == typeof(LookUpEdit))
                {
                    ((LookUpEdit)control).Properties.ReadOnly = !isEnable;
                    ((LookUpEdit)control).Properties.AppearanceReadOnly.BackColor = Color.GhostWhite;
                    ((LookUpEdit)control).Properties.ShowDropDown = (!isEnable) ? ShowDropDown.Never : ShowDropDown.SingleClick;
                }
                if (control.GetType() == typeof(ComboBoxEdit))
                {
                    ((ComboBoxEdit)control).Properties.ReadOnly = !isEnable;
                    ((ComboBoxEdit)control).Properties.AppearanceReadOnly.BackColor = Color.GhostWhite;
                    ((ComboBoxEdit)control).Properties.ShowDropDown = (!isEnable) ? ShowDropDown.Never : ShowDropDown.SingleClick;
                }
                if (control.GetType() == typeof(SimpleButton))
                {
                    ((SimpleButton)control).Enabled = isEnable;
                    ((SimpleButton)control).Appearance.BackColor = Color.GhostWhite;
                }
                if (control.GetType() == typeof(SpinEdit))
                {
                    ((SpinEdit)control).Properties.ReadOnly = !isEnable;
                    ((SpinEdit)control).Properties.AppearanceReadOnly.BackColor = Color.GhostWhite;
                }
                if (control.GetType() == typeof(MemoEdit))
                {
                    ((MemoEdit)control).Properties.ReadOnly = !isEnable;
                    ((MemoEdit)control).Properties.AppearanceReadOnly.BackColor = Color.GhostWhite;
                }
                if (control.GetType() == typeof(GridLookUpEdit))
                {
                    ((GridLookUpEdit)control).Properties.ReadOnly = !isEnable;
                    ((GridLookUpEdit)control).Properties.AppearanceReadOnly.BackColor = Color.GhostWhite;
                    ((GridLookUpEdit)control).Properties.ShowDropDown = (!isEnable) ? ShowDropDown.Never : ShowDropDown.SingleClick;
                }
            }
        }

        #endregion

        #region Functions overrides

        /// <summary>
        /// Shows the help.
        /// </summary>
        protected virtual void ShowHelp()
        {
        }

        /// <summary>
        /// Valids the data.
        /// </summary>
        /// <returns></returns>
        protected virtual bool ValidData()
        {
            return true;
        }

        /// <summary>
        /// Saves the data.
        /// </summary>
        /// <returns></returns>
        protected virtual string SaveData()
        {
            return "";
        }

        /// <summary>
        /// Initializes the data.
        /// </summary>
        protected virtual void InitData()
        {

        }

        /// <summary>
        /// Show detail data.
        /// </summary>
        protected virtual void ShowData()
        {
            InitData();
            InitRefInfo();
            LoadGridDetailLayout();
            SetNumericFormatControl(gridViewDetail, true);
        }

        /// <summary>
        /// Focuses the control.
        /// </summary>
        protected virtual void InitControls()
        {
        }

        /// <summary>
        /// Adds the new voucher.
        /// </summary>
        protected virtual void AddNewVoucher()
        {
            try
            {
                ActionMode = ActionModeEnum.AddNew;
                MasterBindingSource.AddNew();
                MasterBindingSource.MoveLast();
                ShowData();
                GeneratedBaseRefNo();
            }
            catch (Exception ex) { XtraMessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error); }
        }

        /// <summary>
        /// Edits the voucher.
        /// </summary>
        protected virtual void EditVoucher()
        {
            ActionMode = ActionModeEnum.Edit;
        }

        /// <summary>
        /// Deletes the voucher.
        /// </summary>
        protected virtual string DeleteVoucher()
        {
            ActionMode = ActionModeEnum.Delete;
            return "";
        }

        /// <summary>
        /// Cancels the voucher.
        /// </summary>
        protected virtual void CancelVoucher()
        {
            try
            {
                ActionMode = ActionModeEnum.None;
                MasterBindingSource.CancelEdit();
                bindingSourceDetail.CancelEdit();

                if (MasterBindingSource.Count <= 0)
                {
                    Close();
                    return;
                }
                CurrentPosition = MasterBindingSource.Position = BindingContext[MasterBindingSource, MasterBindingSource.DataMember].Position;
                ShowData();
                RefreshNavigationButton();
            }
            catch (Exception ex) { XtraMessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error); }
        }

        /// <summary>
        /// Prints the voucher.
        /// </summary>
        protected virtual void PrintVoucher()
        {

        }

        /// <summary>
        /// Refreshes the voucher.
        /// </summary>
        protected virtual void RefreshVoucher()
        {
            try { ShowData(); }
            catch (Exception ex) { XtraMessageBox.Show(ex.ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Error); }
        }

        /// <summary>
        /// Deletes the row item.
        /// </summary>
        protected virtual void DeleteRowItem()
        {
            gridViewDetail.DeleteSelectedRows();
        }

        /// <summary>
        /// Adds the new row item.
        /// </summary>
        protected virtual void AddNewRowItem()
        {
            gridViewDetail.AddNewRow();
        }

        /// <summary>
        /// Initializes the reference information.
        /// </summary>
        protected virtual void InitRefInfo()
        {
            if (ActionMode != ActionModeEnum.AddNew) return;
            //dtPostDate.EditValue = SystemDate;
            //dtRefDate.EditValue = dtPostDate.EditValue;
        }

        /// <summary>
        /// Sets the enable group box.
        /// </summary>
        /// <param name="isEnable">if set to <c>true</c> [is enable].</param>
        protected virtual void SetEnableGroupBox(bool isEnable)
        {

        }

        #endregion

        public FrmXtraBaseVoucherDetail()
        {
            InitializeComponent();
            _autoNumberPresenter = new AutoNumberPresenter(this);
        }

        private void FrmXtraBaseVoucherDetail_Load(object sender, EventArgs e)
        {
            try
            {
                if (DesignMode) return;
                InitializeLayout();
                ShowData();
                GeneratedBaseRefNo();
                SetNumericFormatControl(gridViewDetail, true);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void barToolManager_ItemClick(object sender, ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "barButtonFirstItem":
                    MoveFirstVoucher();
                    break;
                case "barButtonPreviousItem":
                    MovePreviousVoucher();
                    break;
                case "barButtonNextItem":
                    MoveNextVoucher();
                    break;
                case "barButtonLastItem":
                    MoveLastVoucher();
                    break;
                case "barButtonAddNewItem":
                    AddNewVoucher();
                    break;
                case "barButtonEditItem":
                    EditVoucher();
                    break;
                case "barButtonDeleteItem":
                    DeleteVoucher();
                    break;
                case "barButtonSaveItem":
                    try
                    {
                        if (ValidData())
                        {
                            gridViewDetail.CloseEditor();
                            if (gridViewDetail.UpdateCurrentRow())
                            {
                                var rowAffected = SaveData();
                                if (rowAffected == null)
                                {
                                    if (ActionMode != ActionModeEnum.AddNew)
                                    {
                                        _keyForSend = KeyValue;
                                    }
                                    else
                                    {

                                    }
                                    //   _keyForSend = ActionMode == ActionModeEnum.AddNew ? rowAffected.ToString(CultureInfo.InvariantCulture) : KeyValue;
                                    CloseForm();
                                }
                                //if (rowAffected > 0)
                                //{
                                //    _keyForSend = ActionMode == ActionModeEnum.AddNew ? rowAffected.ToString(CultureInfo.InvariantCulture) : KeyValue;
                                //    CloseForm();
                                //}
                                else
                                {
                                    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResSaveDataError"), ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    XtraMessageBox.Show(rowAffected, ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }


                                //if (rowAffected > 0)
                                //{
                                //    _keyForSend = ActionMode == ActionModeEnum.AddNew ? rowAffected.ToString(CultureInfo.InvariantCulture) : KeyValue;
                                //    CloseForm();
                                //    ActionMode = ActionModeEnum.None;
                                //    RefreshNavigationButton();
                                //}
                                //else XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResSaveDataError"), ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    catch (Exception ex) { XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error); }
                    break;
                case "barButtonCancelItem":
                    CancelVoucher();
                    break;
                case "barButtonRefeshItem":
                    RefreshVoucher();
                    break;
                case "barButtonPrintItem":
                    PrintVoucher();
                    break;
                case "barButtonHelpItem":
                    ShowHelp();
                    break;
                case "barButtonCloseItem":
                    Close();
                    break;
                case "barButtonDeleteRowItem":
                    DeleteRowItem();
                    break;
                case "barButtonAddNewRowItem":
                    AddNewRowItem();
                    break;
            }
        }

        private void gridViewDetail_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void gridViewDetail_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            var view = sender as GridView;
            if (view != null)
            {
                var hitInfo = view.CalcHitInfo(e.Point);
                if (hitInfo.InRow)
                {
                    view.FocusedRowHandle = hitInfo.RowHandle;
                    popupGridDetailMenu.ShowPopup(grdDetail.PointToScreen(e.Point));
                }
            }
        }

        private void gridViewDetail_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            var viewInfo = (GridViewInfo) gridViewDetail.GetViewInfo();
            var rec = new Rectangle(e.Bounds.X + 2, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
            if (e.Column == null) return;
            if (e.Column.Fixed == FixedStyle.Left || e.Column == viewInfo.ColumnsInfo.LastColumnInfo.Column)
            {
                foreach (DevExpress.Utils.Drawing.DrawElementInfo info in e.Info.InnerElements)
                {
                    if (!info.Visible) continue;
                    DevExpress.Utils.Drawing.ObjectPainter.DrawObject(e.Cache, info.ElementPainter, info.ElementInfo);
                }
                e.Painter.DrawCaption(e.Info, e.Info.Caption, e.Appearance.Font, e.Appearance.GetForeBrush(e.Cache), rec, e.Appearance.GetStringFormat());
                e.Graphics.DrawLine(Pens.DarkGray, e.Bounds.Left-1,e.Bounds.Bottom-1, e.Bounds.Right -1, e.Bounds.Bottom -1);
                e.Handled = true;
            }
        }

        private void gridViewMaster_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            var viewInfo = (GridViewInfo) gridViewMaster.GetViewInfo();
            var rec = new Rectangle(e.Bounds.X + 2,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
            
            if (e.Column == null) return;
            if (e.Column.Fixed == FixedStyle.Left || e.Column == viewInfo.ColumnsInfo.LastColumnInfo.Column)
            {
                foreach (DevExpress.Utils.Drawing.DrawElementInfo info in e.Info.InnerElements)
                {
                    if (!info.Visible) continue;
                    DevExpress.Utils.Drawing.ObjectPainter.DrawObject(e.Cache, info.ElementPainter, info.ElementInfo);
                }

                e.Painter.DrawCaption(e.Info, e.Info.Caption, e.Appearance.Font, e.Appearance.GetForeBrush(e.Cache),
                    rec, e.Appearance.GetStringFormat());
                e.Graphics.DrawLine(Pens.DarkGray, e.Bounds.Left - 1, e.Bounds.Bottom - 1, e.Bounds.Right - 1,
                    e.Bounds.Bottom - 1);
                e.Handled = true;
            }
        }
    
public long UnitId
{
	  get 
	{ 
		throw new NotImplementedException(); 
	}
	  set 
	{ 
		throw new NotImplementedException(); 
	}
}

public int RefTypeId
{
	  get 
	{ 
		throw new NotImplementedException(); 
	}
	  set 
	{ 
		throw new NotImplementedException(); 
	}
}
}
}